﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Carbon.Web.Forms
{
    public class Log
    {
        private static readonly String Source = "Carbon.Web.Forms";
        private static readonly String SafeSource = "Application";

        public static void ExecuteWithLog(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }

        public static T CalculateWithLog<T>(Func<T> action)
        {
            try
            {
                return action();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }

        public static void Error(Exception ex)
        {
            if (ex == null)
                ex = new SystemException("Null passed to log function.\n" + Environment.StackTrace);

            try
            {
                EventLog.WriteEntry(Source, ex.ToString(), EventLogEntryType.Error);
            }
            catch
            {

            }

            EventLog.WriteEntry(SafeSource, ex.ToString(), EventLogEntryType.Error);
        }

        public static void Information(String message, params Object[] objects)
        {
            if (message == null)
                message = string.Empty;

            string allMessage = objects != null ? String.Format(message, objects) : message;

            try
            {
                EventLog.WriteEntry(Source, allMessage, EventLogEntryType.Information);
            }
            catch
            {
            }

            EventLog.WriteEntry(SafeSource, allMessage, EventLogEntryType.Information);
        }


        public static void LogToStdOut(Exception ex)
        {
            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine(ex);
        }

    }
}
